﻿using IGGCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace IGG
{
    public class StoryManager
    {
        private NewsParser parser = new NewsParser();
        private Random rnd = new Random();
        private HeymanParser heymanParser = new HeymanParser();
        private NeyerParser neyerParser = new NeyerParser();
        private News selectedNews = null;

        public void LoadStory()
        {
            List<string> feeds = new List<string>();
            List<News> news = new List<News>();

            // SYNDICATE CLASS FROM .NET?
            // HEYMAN PARSER... NEYER PARSER... TIM BROWN... ROSENTHAL...

            feeds.Add("http://joeposnanski.com/joeblogs/feed/"); // JOE POSNANSKI
            feeds.Add("http://rss.cnn.com/rss/si_ben_reiter.rss"); // BEN REITER
            feeds.Add("http://rss.cnn.com/rss/si_tom_verducci.rss"); // TOM VERDUCCI 
            feeds.Add("http://sports.yahoo.com/mlb/blog/big_league_stew/rss.xml"); // KADUK 
            feeds.Add("http://grantland.com/contributors/jonah-keri/feed/"); // KERI
            feeds.Add("http://nypost.com/author/joel-sherman/feed/"); // SHERMAN
            feeds.Add("http://mlb.si.com/author/joelemire/feed/"); // JOE LEMIRE

            List<News> newsHeyman = heymanParser.GetNews("http://www.cbssports.com/writers/jon-heyman", 5); // HEYMAN
            List<News> newsNeyer = neyerParser.GetNews("http://msn.foxsports.com/tag/rob-neyer", 5); // NEYER

            // OK
            // CALCATERRA - http://hardballtalk.nbcsports.com/author/ccalcaterra/feed/
            // JOEL SHERMAN - http://nypost.com/author/joel-sherman/feed/
            // feeds.Add("http://topics.nytimes.com/top/reference/timestopics/people/k/tyler_kepner/index.html?rss=1"); // TYLER KEPNER - COOKIES


            // NOT OK
            // feeds.Add("http://sports.yahoo.com/author/jeff-passan/"); // JEFF PASSAN (CANNOT PARSE)
            // SWEETSPOT / SCHOENFIELD - http://espn.go.com/blog/feed?blog=sweetspot
            // feeds.Add("http://mlb.si.com/author/cliffcorcoransi/"); // CLIFF CORCORAN (CANNOT PARSE)
            // ROSENTHAL - http://feeds.foxsports.com/feedout/syndicatedContent?authorId=162
            // TIM BROWN - http://sports.yahoo.com/author/tim-brown/ 


            // GET MOST RECENT
            // Create a list of news and Sort/Linq them
            foreach(string feed in feeds)
            {
                news.AddRange(parser.GetRssNews(feed, 5, false));
            }
            news.AddRange(newsHeyman); // ADD HEYMAN NEWS
            news.AddRange(newsNeyer); // ADD NEYER NEWS

            var sorted = news.OrderByDescending(x => x.DateObject);
            IEnumerator enume = sorted.GetEnumerator();

            int num = rnd.Next(4) + 1;
            for (int i=0; i<num; i++)
            {
                enume.MoveNext();
            }

            selectedNews = enume.Current as News;
            
        }

        public void FormatStory()
        {
            FormatWholeStory(selectedNews);
        }

        private void FormatWholeStory(News news)
        {
            string whole = news.Content;
            try
            {
                Output.WriteLine();
                
                if (news.Provider != "Jon Heyman" && news.Provider != "Rob Neyer")
                {
                    whole = GetAllContent(news.Link);
                }
                string outp = whole;
                if (news.Provider == "Jon Heyman")
                {
                    Output.WriteLine(" HEYMAN - " + news.Title);
                    outp = outp.Replace("</p>", "");
                    outp = outp.Replace("</div>", "");
                    outp = outp.Replace("<div class=\"storyCopy\">", "");
                    outp = outp.Replace("<figure>", "");
                    outp = outp.Replace("</figure>", "");
                    outp = RemoveParts(outp, "<figcaption");
                    outp = RemoveSingleParts(outp, "<img");
                    outp = RemoveLinks(outp);
                    outp = Titlelize(outp);
                    Output.WriteLine();
                }
                else if (news.Provider == "Rob Neyer")
                {
                    Output.WriteLine(" NEYER - " + news.Title);
                    outp = outp.Replace("<head></head>", "");
                    outp = outp.Replace("<body>", "");
                    outp = outp.Replace("</body>", "");
                    outp = outp.Replace("</div>", "");
                    outp = outp.Replace("</p>", "");
                    outp = RemoveParts(outp, "<noscript>");
                    outp = RemoveParts(outp, "<ul>");
                    outp = RemoveParts(outp, "<h4>");
                    outp = RemoveSingleParts(outp, "<div class");
                    outp = RemoveSingleParts(outp, "<!--");
                    outp = RemoveSingleParts(outp, "<div");
                    outp = RemoveLinks(outp);
                    Output.WriteLine();
                }
                else if (whole.Contains("<div id=\"content\">")) // JOE LEMIRE
                {
                    outp = whole.Substring(whole.IndexOf("<div id=\"content\">"));
                    outp = outp.Substring(outp.IndexOf("<p>"));
                    outp = outp.Replace("</span>", "");
                    outp = RemoveSingleParts(outp, "<span");
                    outp = outp.Replace("</p>", "");
                    outp = outp.Replace("<br />", Environment.NewLine + " ");
                    outp = outp.Substring(0, outp.IndexOf("<!-- /.body -->"));
                    outp = RemoveParts(outp, "<strong>");
                    outp = RemoveParts(outp, "<div");
                    outp = RemoveLinks(outp);
                    outp = Titlelize(outp);
                    outp = outp.Replace("</div>", "");
                    Output.WriteLine(" JOE LEMIRE - " + news.Title);
                    Output.WriteLine();
                }
                else if (whole.Contains("cnnContentPage")) // SI STORIES
                {
                    outp = whole.Substring(whole.IndexOf("cnnContentPage"));
                    outp = outp.Substring(outp.IndexOf("<p>"));
                    outp = outp.Replace("<!--startclickprintexclude-->", "");
                    outp = outp.Replace("<!--endclickprintexclude-->", "");
                    outp = outp.Replace("</div>", "");
                    outp = outp.Replace("<div class=\"cnnDivideContent\">", "");
                    outp = outp.Replace("</p>", "");
                    outp = outp.Replace("\n", "");
                    outp = outp.Substring(0, outp.IndexOf("<script"));
                    outp = FormatTables(outp);
                    outp = RemoveParts(outp, "<strong>");
                    outp = RemoveLinks(outp);
                    Output.WriteLine(" " + news.Title);
                    Output.WriteLine();
                }
                else if (whole.Contains("entry-content")) // POSNANSKI - SHERMAN
                {
                    outp = whole.Substring(whole.IndexOf("entry-content"));
                    outp = outp.Substring(outp.IndexOf("<p>"));
                    outp = outp.Replace("</div>", "");
                    outp = outp.Replace("</p>", "");
                    outp = outp.Replace("<br />", "");
                    outp = outp.Replace("\n", "");
                    if (outp.IndexOf(".entry-content") >-1)
                    { 
                        outp = outp.Substring(0, outp.IndexOf(".entry-content"));
                        if (outp.IndexOf("<div class=") > -1)
                        {
                            outp = outp.Substring(0, outp.IndexOf("<div class="));
                        }
                        Output.WriteLine(" POSNANSKI - " + news.Title);
                    }
                    else
                    {
                        outp = outp.Substring(0, outp.IndexOf("<div id=\"jp"));
                        Output.WriteLine(" JOEL SHERMAN - " + news.Title);
                    }
                    outp = RemoveParts(outp, "<strong>");
                    outp = RemoveParts(outp, "<span");
                    outp = RemoveLinks(outp);
                    Output.WriteLine();
                }
                else if (whole.Contains("<meta itemprop=\"description\" content=")) // KADUK
                {
                    outp = whole.Substring(whole.IndexOf("<meta itemprop=\"description\" content="));
                    outp = outp.Substring(0, outp.IndexOf("<div id=\"mediacontentcomments\""));
                    outp = outp.Substring(0, outp.IndexOf("<p id"));
                    outp = outp.Substring(outp.IndexOf("</p>"));
                    outp = outp.Replace("</p></div></p>", "");
                    outp = outp.Trim();
                    outp = outp.Replace("</p>", "");
                    outp = outp.Replace("(Getty)", "");
                    outp = outp.Replace("(USA Today)", "");
                    outp = outp.Replace("(AP)", "");
                    outp = outp.Replace("</figure>", "");
                    outp = outp.Replace("<strong>", "");
                    outp = outp.Replace("</strong>", "");
                    outp = outp.Replace("</div>", "");
                    outp = outp.Replace("<p class=\"legend\">", "");
                    outp = outp.Replace("(Getty Images)", "");
                    outp = outp.Replace("<p class=\"cta-text large\">View gallery", "");
                    outp = RemoveParts(outp, "<span");
                    outp = outp.Replace("</span>", "");
                    outp = RemoveSingleParts(outp, "<img");
                    outp = RemoveSingleParts(outp, "<figure");
                    outp = RemoveSingleParts(outp, "<blockquote");
                    outp = RemoveSingleParts(outp, "<div class");
                    outp = RemoveLinks(outp);
                    Output.WriteLine(" BIG LEAGUE STEW - " + news.Title);
                    Output.WriteLine();
                }
                else if (whole.Contains("<div class=\"article-body")) // KERI-1
                {
                    outp = whole.Substring(whole.IndexOf("<div class=\"article-body\">") + "<div class=\"article-body\"".Length + 1);
                    if (outp.IndexOf("<div class=\"social>") > -1)
                    {
                        outp = outp.Substring(0, outp.IndexOf("<div class=\"social>"));
                    }
                    outp = outp.Replace("</p>", "");
                    outp = outp.Replace("</span>", "");
                    outp = RemoveSingleParts(outp, "<span");
                    outp = RemoveParts(outp, "<noscript");
                    outp = RemoveLinks(outp);
                    Output.WriteLine(" KERI - " + news.Title);
                    Output.WriteLine();
                }
                else if (whole.Contains("<div class=\"blog-body")) // KERI-2
                {
                    outp = whole.Substring(whole.IndexOf("<div class=\"blog-body\">") + "<div class=\"blog-body\"".Length + 1);
                    outp = outp.Substring(0, outp.IndexOf("<div class=\"article-share"));
                    outp = outp.Replace("</p>", "");
                    outp = outp.Replace("</span>", "");
                    outp = RemoveSingleParts(outp, "<span");
                    outp = RemoveParts(outp, "<noscript");
                    outp = RemoveLinks(outp);
                    Output.WriteLine(" KERI - " + news.Title);
                    Output.WriteLine();
                }

                // GENERAL FORMATTING
                
                outp = outp.Replace("&#8212;", "-");
                outp = outp.Replace("&#8211;", "-");
                outp = outp.Replace("&#8230;", "...");
                outp = outp.Replace("&#8220;", "\"");
                outp = outp.Replace("&#8221;", "\"");
                outp = outp.Replace("&#8217;", "'");
                outp = outp.Replace("&#040;", "(");
                outp = outp.Replace("&#041;", ")");
                outp = outp.Replace("&#34;", "\"");
                outp = outp.Replace("&#36;", "$");
                outp = outp.Replace("&#034;", "\"");
                outp = outp.Replace("&#036;", "$");
                outp = outp.Replace("&ldquo;", "\"");
                outp = outp.Replace("&rdquo;", "\"");

                outp = outp.Replace("</em>", "");
                outp = outp.Replace("<em>", "");
                outp = outp.Replace("&nbsp;", " ");
                outp = outp.Replace("</i>", "");
                outp = outp.Replace("<i>", "");
                outp = outp.Replace("</b>", "");
                outp = outp.Replace("<b>", "");
                outp = outp.Replace("&hellip;", "...");
                outp = outp.Replace("<blockquote>", "");
                outp = outp.Replace("</blockquote>", "");


                string[] splits = outp.Split(new string[] { "<p>" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string line in splits)
                {
                    if (line.Trim() != string.Empty)
                    {
                        Output.FormatLongText(line.Trim());
                        Output.WriteLine();
                    }
                }
            }
            catch(Exception ex)
            {
                Output.WriteLine();
                Output.WriteLine(" UNABLE TO FORMAT STORY FROM " + news.Provider);
                Output.WriteLine();
                Output.WriteLine(" " + news.Content);
                string raw = news.Provider + Environment.NewLine;
                raw += news.Link + Environment.NewLine +Environment.NewLine;
                raw += ex.Message + Environment.NewLine;
                raw += ex.StackTrace + Environment.NewLine + Environment.NewLine;
                raw += whole;
                DebugManager.GetInstance().Debug("story", raw);
                throw ex;
            }
            
        }

        private string Titlelize(string input)
        {
            string result = input;
            int found = result.IndexOf("<h2>");
            while (found > -1)
            {
                int end = result.IndexOf("<", found + 4);
                string newTitle = Environment.NewLine + Environment.NewLine + " " + result.Substring(found + 4, end - found - 4).ToUpper() + Environment.NewLine;
                result = result.Remove(found, end - found);
                result = result.Insert(found, newTitle);
                found = result.IndexOf("<h2>");
            }
            result = result.Replace("</h2>", "");
            result = result.Replace("</H2>", "");
            return result;
        }

        private string RemoveLinks(string input)
        {
            string result = input;
            int found = result.IndexOf("<a ");
            while(found > -1)
            {
                int end = result.IndexOf(">", found);
                result = result.Remove(found,end - found + 1);
                found = result.IndexOf("<a ");
            }
            result = result.Replace("</a>", "");
            return result;
        }

        private string RemoveParts(string input, string tag)
        {
            string result = input;
            string endtag = tag.Replace("<", "</");
            if (endtag.EndsWith(">") == false)
            {
                endtag = endtag + ">";
            }
            int found = result.IndexOf(tag);
            while (found > -1)
            {
                int end = result.IndexOf(endtag, found);
                result = result.Remove(found, end - found + endtag.Length);
                found = result.IndexOf(tag);
            }
            return result;
        }

        private string RemoveSingleParts(string input, string tag)
        {
            string result = input;
            int found = result.IndexOf(tag);
            while (found > -1)
            {
                int end = result.IndexOf(">", found);
                result = result.Remove(found, end - found + 1);
                found = result.IndexOf(tag);
            }
            return result;
        }

        private string GetCell(string raw, string tag)
        {
            string result = null;
            int index = raw.IndexOf(tag);
            if (index>-1)
            {
                int start = raw.IndexOf(">", index)+1;
                int end = raw.IndexOf("<", start);
                int count = end - start;
                result = raw.Substring(start, count);
            }
            return result;
        }

        private List<string> GetColumnTitles(string raw)
        {
            List<string> titles = new List<string>();

            int found = raw.IndexOf("<th");
            while (found > -1)
            {
                int start = raw.IndexOf(">", found);
                int end = raw.IndexOf("<", start);
                titles.Add(raw.Substring(start + 1, end - start - 1));
                found = raw.IndexOf("<th", found + 3);
            }

            return titles;
        }

        private string FormatTables(string input)
        {
            string result = input;
            string endtag = "</table>";
            if (endtag.EndsWith(">") == false)
            {
                endtag = endtag + ">";
            }
            int found = result.IndexOf("<table");
            while (found > -1)
            {
                int end = result.IndexOf(endtag, found);
                string tableraw = result.Substring(found, end - found + endtag.Length);
                string formatted = Environment.NewLine;
                string title = GetCell(tableraw, "<td class=\"cnnIEBoxTitle\">");
                if (title!=null)
                {
                    formatted = Environment.NewLine + " " + title.ToUpper();
                }
                List<string> titles = GetColumnTitles(tableraw);
                formatted += Environment.NewLine + " ";
                foreach(string line in titles)
                {
                    formatted += ToolBox.GetFormattedStringPadRight(line, 25);
                }
                result = result.Remove(found, end - found + endtag.Length);

                result = result.Insert(found, formatted);
                found = result.IndexOf("<table");
            }
            result = result.Replace("<tr><td class=\"cnnTMfooter\"></td></tr>", "");
            result = result.Replace("</td></tr>", "");
            result = result.Replace("</table>", "");
            return result;
        }

        private string GetAllContent(string url)
        {
            string transContent = null;
            var cookieContainer = new CookieContainer();
            StreamReader reader = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.CookieContainer = cookieContainer;
                reader = new StreamReader(request.GetResponse().GetResponseStream());
                transContent = reader.ReadToEnd();
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return transContent;
        }
    }
}
